import random

from rest_framework import status

from celery_tasks.sms.tasks import send_sms_code
from users.models import User
from rest_framework.response import Response
from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from django_redis import get_redis_connection
from django_redis import get_redis_connection
from verifications.serializers import ImageCodeCheckSerializer
from . import constants
from django.http import HttpResponse
from meiduo_mall.libs.captcha.captcha import captcha
import logging
# Create your views here.
logger = logging.getLogger('django')


# 判断手机号是否存在
# mobiles/(?P<mobile>1[3-9]\d{9})/count
class MobileCountView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            'mobile': mobile,
            'count': count
        }
        return Response(data)


# 判断账号是否存在
# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        data = {
            'count': count,
            'username': username
        }
        return Response(data)



# /image_codes/(?P<image_code_id>[\w-]+)/
# 图形验证码的实现逻辑
class ImageCodeView(APIView):
    def get(self, request, image_code_id):
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.setex('img_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        return HttpResponse(image, content_type='images/jpg')


# /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id=xxx&text=xxx
# 短信验证码的实现逻辑
class SMSCodeView(GenericAPIView):

    serializer_class = ImageCodeCheckSerializer
    def get(self, request, mobile):
        # 获取参数
        serializer = self.get_serializer(data=request.query_params)
        # 校验参数　# 关于涉及到查询验证信息交给序列器来完成
        # 关于校验，验证的错误代码都会返回４００
        serializer.is_valid(raise_exception=True)
        # 调用容联云发送短信
        sms_code = '%06d' % random.randint(0, 999999)
        # 保存数据到ｒｅｄｉｓ
        print(sms_code)
        redis_conn = get_redis_connection('verify_codes')
        # 创建管道
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        # try:
        #     ccp = CCP()
        # # ccp.send_template_sms('18516952650', ['1234', 5], 1)
        #     expires = constants.SMS_CODE_REDIS_EXPIRES//60
        #     result = ccp.send_template_sms(mobile, [sms_code, expires], constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error("发送验证码短信[异常][ mobile: %s, message: %s ]" % (mobile, e))
        #     return Response(data={'message': '第三方框架错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        #     if result == 0:
        #         return Response(data={'message': '发送成功'}, status=status.HTTP_200_OK)
        #     else:
        #         return Response(data={'message': '发送失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # send_sms_code.delay(mobile, sms_code)

        return Response(data={'message': '发送成功'}, status=status.HTTP_200_OK)





